import jwt
from flask import Blueprint, jsonify, current_app ,send_file
from flask_restful import Api, Resource,reqparse
from utils.smscode import sms_code
from utils.myredis import r
from models.user.user import User,db
from captcha.image import ImageCaptcha

from utils.myjwt import mjwt

login_bp = Blueprint('login_bp', __name__, url_prefix='/')
api = Api(login_bp)

import random
import time

# 图片验证码
class ImgView(Resource):
    def get(self):
        req = reqparse.RequestParser()
        req.add_argument('uuid')
        args = req.parse_args()
        img = ImageCaptcha()
        code = random.randint(1000,9999)
        code1 = str(code)
        img_png = img.generate(code1)
        r.ser_add(args['uuid'],code1,3600)
        return send_file(img_png,mimetype="png")

api.add_resource(ImgView,'/img')

# 发送手机验证码
class SendSmsCode(Resource):
    def post(self):
        req = reqparse.RequestParser()
        req.add_argument('uuid')
        req.add_argument('mobile')
        req.add_argument('piccode')
        args = req.parse_args()
        print(args['piccode'],1231231)

        # 从redis中取出来 图片验证码
        value = r.str_get(args['uuid'])
        if value:
            if args['piccode'] == value.decode():
                print(value.decode(),222222)
                # 验证一分钟内只能发一次
                mcode = r.str_get(args['mobile'])
                if mcode:
                    return jsonify({'code':10012,'msg':'一分钟内不能重复发'})
                # 调用短信平台
                # 生成5位随机数
                smscode = str(random.randint(1000, 9999))
                flag = sms_code(args['mobile'], smscode)
                if flag:
                    # 手机验证码存入redis
                    r.ser_add(args['mobile'],smscode,60)
                    # 删除图片验证码
                    r.del_str(args['uuid'])
                    # 返回结果
                    return jsonify({'code':200,'msg':'发送成功'})
                else:
                    return jsonify({'code': 10013, 'msg': '发送验证码失败'})
            else:
                return jsonify({'code':10011,'msg':'图片验证码错误'})
        else:
            return jsonify({'code': 10010, 'msg': '图片验证码不存在'})

api.add_resource(SendSmsCode,'/sendSmsCode')


# 登录接口
class LoginView(Resource):
    def post(self):
        req = reqparse.RequestParser()
        req.add_argument('smscode')
        req.add_argument('mobile')
        args = req.parse_args()
        # 判断数据是否存在
        if not all([args['smscode'],args['mobile']]):
            return jsonify({
                'code':400,
                'msg':'数据不完整'
            })
        # 从redis中取出  验证码
        code = r.str_get(args['mobile'])
        if code:
            print(code,55555)
            # 判断验证码是否相同
            if int(code.decode()) == int(args['smscode']):
                user = User.query.filter(User.mobile == args['mobile']).first()
                print(user,111111)
                # 如果相同 删除验证码（为了节约内存）
                # 否则  存入到用户表中
                if user:
                    r.del_str(args['mobile'])
                else:
                    u = User(mobile=args['mobile'],nikename=args['mobile'])
                    db.session.add(u)
                    db.session.commit()
                    user = User.query.filter(User.mobile == args['mobile']).first()
                # 生成一个token  key加盐
                # 返回token给前端  用户id也返回过去

# key = current_app.config.get('SECRET_KEY')
# token = jwt.encode({
#     'user_id':user.id,
#     'exp': int(time.time()) + 180
# },key,algorithm='HS256')

                token = mjwt.jwt_encode({'user_id':user.id,'exp':int(time.time())})
                return jsonify({
                    'code':200,
                    'msg':'登录成功',
                    'token':token,
                    'user_id':user.id
                })
            else:
                return jsonify({'code':400,'msg':'验证码错误'})
        else:
            return jsonify({'code':400,'msg':'验证码已过期'})


api.add_resource(LoginView,'/login')



# 测试
class Test(Resource):
    def get(self):
        return jsonify({
            'code':200,
            'msg':'msg'
        })
api.add_resource(Test,'/test')

